# -*- coding: utf-8 -*-
from flask import Blueprint, g
from sqlalchemy import or_
from common.response import success, error
from filter.auth import auth_required
from common.error_code import ErrorCode
from filter.decorators import validate_request, require_role
from model.request import ListTeachersRequest, EditTeacherRequest
from dao.db import db
from dao.user_dao import Student, User, Teacher, Class
from dao.class_dao import ClassSubjectTeacher

# 创建教师管理蓝图
teachermgr_bp = Blueprint('teachermgr', __name__, url_prefix='/api/teachermgr')

@teachermgr_bp.route('/list-teachers', methods=['POST'])
@auth_required
@require_role(['admin', 'teacher', 'student'])
@validate_request(ListTeachersRequest)
def list_teachers():
    """列出符合条件的教师信息"""
    params = g.request_data
    name_keyword = params.name.strip() if params.name else None
    target_class_id = params.class_id

    # 学生只能查看自己班级的老师
    if g.role == 'student':
        current_student = Student.query.filter_by(user_id=g.user_id).first()
        if not current_student:
            return error(ErrorCode.FORBIDDEN, "学生信息不存在")
        target_class_id = current_student.class_id

    # --------------------------
    # 步骤1：基础查询（关联User和Teacher表）
    # --------------------------
    # 核心查询：关联教师表和用户表，获取基础信息
    base_query = db.session.query(
        Teacher.id.label('teacher_id'),  # 教师ID
        User.id.label('user_id'),        # 用户ID
        User.name.label('teacher_name'), # 教师姓名
        Teacher.position.label('position'), # 教师职务
        Teacher.password_hash.label('teacher_password') # 教师口令
    ).join(
        User, Teacher.user_id == User.id  # 关联用户表
    )

    # --------------------------
    # 步骤2：按姓名模糊筛选（可选）
    # --------------------------
    if name_keyword:
        base_query = base_query.filter(User.name.like(f'%{name_keyword}%'))

    # --------------------------
    # 步骤3：按负责班级筛选（可选）
    # 逻辑：目标班级的班主任 + 目标班级的所有任课老师
    # --------------------------
    # 存储“教师ID-班级角色”的映射（用于后续返回角色信息）
    teacher_class_role = {}
    if target_class_id:
        # 3.1 验证目标班级是否存在
        target_class = Class.query.get(target_class_id)
        if not target_class:
            return error(ErrorCode.NOT_FOUND, f"班级ID={target_class_id}不存在")

        # 3.2 查目标班级的班主任（1位）
        head_teacher = Teacher.query.filter_by(
            id = target_class.head_teacher_id
        ).first()
        if head_teacher:
            teacher_class_role[head_teacher.id] = "班主任"

        # 3.3 查目标班级的所有任课老师（多位）
        subject_teachers = db.session.query(
            ClassSubjectTeacher.teacher_id,
            ClassSubjectTeacher.subject
        ).filter_by(class_id=target_class_id).all()
        for teacher_id, subject in subject_teachers:
            if teacher_id in teacher_class_role:
                teacher_class_role[teacher_id] += f";{subject}老师"
            else:
                teacher_class_role[teacher_id] = f"{subject}老师"

        # 3.4 筛选：仅保留“班主任+任课老师”
        valid_teacher_ids = list(teacher_class_role.keys())
        base_query = base_query.filter(Teacher.id.in_(valid_teacher_ids))

    # --------------------------
    # 步骤4：执行查询并格式化返回
    # --------------------------
    teacher_list = base_query.all()
    result = []
    for teacher in teacher_list:
        item = {
            "user_id": teacher.user_id,
            "teacher_id": teacher.teacher_id,
            "teacher_name": teacher.teacher_name,
            "position": teacher.position,
            "teacher_password": teacher.teacher_password  # 教师口令
        }
        # 若指定了班级筛选，添加“班级角色”字段
        if target_class_id and teacher.teacher_id in teacher_class_role:
            item["class_role"] = teacher_class_role[teacher.teacher_id]
            item['subject'] = teacher_class_role[teacher.teacher_id].replace('老师', '')
        result.append(item)

    return success(result)

@teachermgr_bp.route('/edit-teacher', methods=['POST'])
@auth_required
@require_role(['admin'])
@validate_request(EditTeacherRequest)
def edit_teacher():
    """管理员编辑教师信息"""
    data = g.request_data

    # 1. 验证管理员口令
    admin_teacher = Teacher.query.filter_by(user_id=g.user_id).first()
    if not admin_teacher:
        return error(ErrorCode.FORBIDDEN, "当前用户不是教师，无法验证口令")

    if admin_teacher.password_hash != data.admin_password:
        return error(ErrorCode.INVALID_PARAM, "管理员口令错误")

    # 2. 查找教师
    teacher_user = User.query.filter(User.id == data.user_id,User.role.in_(['teacher', 'admin'])).first()
    if not teacher_user:
        return error(ErrorCode.NOT_FOUND, "教师不存在")

    teacher_info = Teacher.query.filter_by(user_id=data.user_id).first()
    if not teacher_info:
        return error(ErrorCode.NOT_FOUND, "教师信息不存在")

    # 3. 更新字段（有值才更新）
    if data.name is not None:
        teacher_user.name = data.name

    if data.position is not None:
        teacher_info.position = data.position

    if data.teacher_password is not None:
        # 教师口令存储在 Teacher.password_hash
        teacher_info.password_hash = data.teacher_password

    db.session.commit()

    return success({
        "user_id": teacher_user.id,
        "name": teacher_user.name,
        "position": teacher_info.position
    })